package com.ujn.demo.common;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CommonUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * 判断是否周末
     * @param bDate
     * @return
     * @throws ParseException
     */
    public static String isWeekend(String bDate) throws ParseException {
        DateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
        Date bdate = format1.parse(bDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(bdate);
        if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
            return "-周末";
        } else{
            return "";
        }
    }

    /**
     * 计算两个时间差(XX:XX)，返回为分钟。
     * @param time1
     * @param time2
     * @return
     */
    public static int callTime(String time1, String time2) {
        DateFormat df = new SimpleDateFormat("HH:mm");
        long minutes = 0L;
        try {
            Date d1 = df.parse(time1);
            Date d2 = df.parse(time2);
            //这样得到的差值是微秒级别
            long diff = d1.getTime() - d2.getTime();
            minutes = diff / (1000 * 60);
        } catch (ParseException e) {
            LOGGER.error("callTime,time1:{}, time2:{}, 抱歉，时间日期解析出错e:{}", time1, time2, e.getMessage());
        }
        return (int) minutes;
    }

    /**
     * 针对str格式的时间做转换 格式为"xx:xx"
     * @param time  传入的时间
     * @param hour  true：返回小时；false：返回分钟
     * @return  当前小时或分钟
     */
    public static int getHourOrMinute(String time, boolean hour){
        if (hour){
            return Integer.parseInt(time.substring(0,time.indexOf(":")));
        }else{
            return  Integer.parseInt(time.substring(time.indexOf(":")+1));
        }
    }

    /**
     * 获取时间
     * @return
     */
    public static String getTime(){
        Date currentTime = new Date();
        //改变输出格式（自己想要的格式）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        //得到字符串时间
        String time = formatter.format(currentTime);
        return time;
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if(c.get(Calendar.DAY_OF_WEEK) == 1){
            dayForWeek = 7;
        }else{
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    @Test
    public void test() throws Exception {
        System.out.println(dayForWeek("2021/04/03"));
    }
}
